package com.dqp.cslggroup.Library;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.text.InputType;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dd.morphingbutton.impl.IndeterminateProgressButton;
import com.dqp.cslggroup.Api.appApi;
import com.dqp.cslggroup.ConnectSever.SeverIP;
import com.dqp.cslggroup.EventBus.MessageEvent;
import com.dqp.cslggroup.ProgressButton.LinearProgressButtonUtil;
import com.dqp.cslggroup.R;
import com.dqp.cslggroup.UI.BaseActivity;
import com.dqp.cslggroup.UI.MyApplication;
import com.dqp.cslggroup.Util.NetCheckUtil;
import com.dqp.cslggroup.Util.SharedPreferencesUtil;
import com.dqp.cslggroup.Util.ToastUtil;
import com.dqp.cslggroup.Util.UiUtils;
import com.dqp.cslggroup.Web.myWeb;
import com.dqp.cslggroup.bean.Club;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Map;

import static com.dqp.cslggroup.UI.MyApplication.getContext;

public class Login_library extends BaseActivity {
    private EditText id, pwd, yz;
    private Button login;
    private String url = "http://10.28.60.4:8080";
    private String use_url;
    private Map<String, String> cookie = null;
    private Handler handler;
    private ImageView yz_img;
    private Connection connection;
    private Connection.Response response;
    private Document document;
    private String user, passward, yzm;
    private TextView tip;
    private SharedPreferences sp;
    private SharedPreferences.Editor editor;
    private RadioButton nei, wai;
    private int flag = 0;
    private IndeterminateProgressButton btnMorph1;
    private String Authorization = SharedPreferencesUtil.getStringSp(MyApplication.getContext(), "Authorization", "");

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_jwxt);
        EventBus.getDefault().register(this);
        initCmp();
        selLoginImg("lib");
        rem_password();
        selectUrl();
        LinearLayout root_view = findViewById(R.id.root_view);
        UiUtils.addLayoutListener(root_view, tip);
        if (NetCheckUtil.checkNet(Login_library.this)) libarary();
        else ToastUtil.showToast("请连接网络！");
    }

    public void selLoginImg(String stype) {
        new Thread(() -> {
            Club club;
            ArrayList<Club> dataList = appApi.getLoginImg();
            for (int i = 0; i < dataList.size(); i++) {
                club = dataList.get(i);
                if (club.getClub_des().equals(stype)) {
                    EventBus.getDefault().post(new MessageEvent("Login_library", 2, club));
                }
            }

        }).start();
    }


    private void selectUrl() {
        if (nei.isChecked()) {
            flag = 0;
            use_url = url;
            tip.setText("请连接校园网后登录！");
            handler = new Handler();
            handler.postDelayed(() -> new LibPicThread().start(), 300);
        } else if (wai.isChecked()) {
            flag = 0;
            SharedPreferences sp;
            SharedPreferences.Editor editor;
            sp = PreferenceManager.getDefaultSharedPreferences(this);
            editor = sp.edit();
            String ip = sp.getString("ip", SeverIP.getDefvalueUrl());
            editor.apply();
            use_url = ip + ":8885";
            tip.setText("初始密码为身份证后六位");
            handler = new Handler();
            handler.postDelayed(() -> new LibPicThread().start(), 300);
        }
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        if (item.getItemId() == android.R.id.home) {
            this.finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    public void rem_password() {
        sp = PreferenceManager.getDefaultSharedPreferences(this);
        pwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        boolean isRemember = sp.getBoolean("remember_lib_password", false);
        if (isRemember) {
            user = sp.getString("stuNum_lib", "");
            passward = sp.getString("password_lib", "");
            id.setText(user);
            pwd.setText(passward);
            editor = sp.edit();
            editor.putBoolean("remember_lib_password", true);
            editor.putString("stuNum_lib", user);
            editor.putString("password_lib", passward);
            editor.apply();
        }
    }

    private void initCmp() {
        id = findViewById(R.id.jwxt_username);
        pwd = findViewById(R.id.jwxt_password);
        yz = findViewById(R.id.jwxt_yz);
        yz_img = findViewById(R.id.jwxt_verimg);
        TextView tishi = findViewById(R.id.jwxt_frag_tv_tishi);
        tishi.setVisibility(View.GONE);
        tip = findViewById(R.id.jwxt_frag_tv_tip);
        nei = findViewById(R.id.jwxt_nei);
        wai = findViewById(R.id.jwxt_wai);
        tip.setText("初始密码为身份证后六位");
        LinearLayout relativeLayout = findViewById(R.id.jwxt_yz_rel);
        relativeLayout.setVisibility(View.VISIBLE);
        RadioGroup radioGroup = findViewById(R.id.wang);
        Button quick = findViewById(R.id.quick_login);
        quick.setVisibility(View.VISIBLE);
        radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
            if (nei.isChecked()) {
                flag = 0;
                use_url = url;
                handler = new Handler();
                handler.postDelayed(() -> new LibPicThread().start(), 300);
            } else if (wai.isChecked()) {
                flag = 0;
                SharedPreferences sp;
                SharedPreferences.Editor editor;
                sp = PreferenceManager.getDefaultSharedPreferences(this);
                editor = sp.edit();
                String ip = sp.getString("ip", SeverIP.getIp().getString("ip"));
                editor.apply();
                use_url = ip + ":8885";
                handler = new Handler();
                handler.postDelayed(() -> new LibPicThread().start(), 300);
            }
        });
        quick.setOnClickListener(v -> {
            Intent intent = new Intent(Login_library.this, myWeb.class);
            intent.putExtra("url", "http://libwx.cslg.edu.cn/m/opac/search.action");
            startActivity(intent);
        });
    }

    @SuppressLint("HandlerLeak")
    private void libarary() {
        InputMethodManager manager = ((InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE));
        btnMorph1 = findViewById(R.id.btnMorph);
        LinearProgressButtonUtil progressButtonUtil = new LinearProgressButtonUtil(getContext());
        progressButtonUtil.IPBmorphToSquare(btnMorph1, 0);
        btnMorph1.setOnClickListener(view -> {
            if (id.getText().toString().isEmpty()) {
                ToastUtil.showToast("请输入学号！");
            } else if (pwd.getText().toString().isEmpty()) {
                ToastUtil.showToast("请输入密码！");
            } else if (yz.getText().toString().length() < 4) {
                ToastUtil.showToast("请输入正确验证码！");
            } else {
                if (manager != null)
                    manager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                if (btnMorph1.getText().equals("登录")) {
                    progressButtonUtil.IPBonMorphButtonClicked(btnMorph1);
                    login();
                } else
                    progressButtonUtil.IPBmorphToSquare(btnMorph1, progressButtonUtil.integer(R.integer.mb_animation));
            }
        });
        yz_img.setOnClickListener(view -> new LibPicThread().start());
    }

    public class LibPicThread extends Thread {
        @Override
        public void run() {
            Connection.Response response;
            try {
                response = Jsoup.connect(use_url + "/reader/captcha.php")
                        .ignoreContentType(true)
                        .header("Authorization", Authorization)
                        .userAgent("Mozilla")
                        .method(Connection.Method.GET)
                        .timeout(3000)
                        .execute();
                cookie = response.cookies();
                byte[] bytes = response.bodyAsBytes();
                Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                EventBus.getDefault().post(new MessageEvent("Login_library", 3, bitmap));
                flag = 1;
            } catch (IOException e) {
                e.printStackTrace();
                ToastUtil.showToast("获取验证码失败！");
            }
        }
    }


    public void login() {
        if (flag == 1) {
            user = id.getText().toString();
            passward = pwd.getText().toString();
            yzm = yz.getText().toString();
            new Thread(() -> {
                try {
                    connection = Jsoup.connect(use_url + "/reader/redr_verify.php");
                    connection.header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                    connection.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
                    connection.header("Authorization", Authorization);
                    connection.data("number", user);
                    connection.data("passwd", passward);
                    connection.data("captcha", yzm);
                    connection.data("select", "cert_no");
                    connection.data("returnUrl", "");
                    connection.cookies(cookie)
                            .ignoreContentType(true)
                            .method(Connection.Method.POST)
                            .timeout(5000)
                            .execute();
                    response = connection.execute();
                    document = Jsoup.parse(response.body());
                    String name = document.select("span[class=profile-name]").text();
                    String card = document.select("div[class=profile-info-value]").select("span").text();
                    String max = document.select("div[class=profile_right]").select("span[class=bigger-170]").text();
                    String chao = document.select("span[class=infobox-data-number]").text();
                    String num = document.select("span[class=Num]").text();
                    if (name.length() > 0) {
                        editor = sp.edit();
                        editor.putBoolean("remember_lib_password", true);
                        editor.putString("stuNum_lib", user);
                        editor.putString("password_lib", passward);
                        editor.apply();
                        response = Jsoup.connect(use_url + "/reader/book_lst.php")
                                .ignoreContentType(true)
                                .header("Authorization", Authorization)
                                .userAgent("Mozilla")
                                .method(Connection.Method.GET)
                                .cookies(cookie)
                                .execute();
                        document = Jsoup.parse(response.body());
                        String dqjy = document.select("b[class=blue]").text();
                        String book = document.select("td[class=whitetext]").text();
                        EventBus.getDefault().post(new MessageEvent("Login_library", 0, null));
                        finish();
                        Intent intent = new Intent(Login_library.this, lib_main.class);
                        intent.putExtra("name", name);
                        intent.putExtra("card", card);
                        intent.putExtra("chao", chao);
                        intent.putExtra("num", num);
                        intent.putExtra("max", max);
                        intent.putExtra("dqjy", dqjy);
                        intent.putExtra("book", book);
                        intent.putExtra("cookies", (Serializable) cookie);
                        intent.putExtra("url", use_url);
                        intent.setClass(Login_library.this, lib_main.class);
                        startActivity(intent);
                    } else {
                        EventBus.getDefault().post(new MessageEvent("Login_library", 4, null));
                        new LibPicThread().start();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    EventBus.getDefault().post(new MessageEvent("Login_library", 1, null));
                }
            }).start();
        } else {
            if (nei.isChecked())
                ToastUtil.showToast("未连接校园网！无法进行登录！");
            else ToastUtil.showToast("获取验证码失败！");
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getEvent().equals("Login_library")) {
            if (event.getWhat() == 0) {
                LinearProgressButtonUtil buttonUtil = new LinearProgressButtonUtil(this);
                buttonUtil.IPBmorphToSuccess(btnMorph1);

            }
            if (event.getWhat() == 1) {
                LinearProgressButtonUtil buttonUtil = new LinearProgressButtonUtil(this);
                buttonUtil.IPBmorphToFailure(btnMorph1, buttonUtil.integer(R.integer.mb_animation));
                ToastUtil.showToast("登陆失败！");
            }
            if (event.getWhat() == 2) {
                ImageView bg = findViewById(R.id.jwxt_img);
                TextView title = findViewById(R.id.jwxt_img_title);
                Club club = (Club) event.getObj();
                title.setText(club.getClub_name());
                Glide.with(Login_library.this).load(club.getClub_img()).into(bg);
            }
            if (event.getWhat() == 3) {
                yz_img.setImageBitmap((Bitmap) event.getObj());
            }
            if (event.getWhat() == 4) {
                LinearProgressButtonUtil buttonUtil = new LinearProgressButtonUtil(this);
                buttonUtil.IPBmorphToFailure(btnMorph1, buttonUtil.integer(R.integer.mb_animation));
                yz.setText("");
                ToastUtil.showToast("请检查账号和密码以及验证码是否正确！");
            }

        }
    }

}